

//
//  GenerateQRCode.m
//  成品家
//
//  Created by YYY on 2017/3/7.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

#import "GenerateQRCode.h"

static CGColorSpaceRef colorSpace;
static CGImageRef scaledImage;

@implementation GenerateQRCode

//字符串生成二维码
+(UIImage *)generateQRCode:(NSString *)codeString
{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [codeString dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];
    CIImage *outputImg = [filter outputImage];
    //改变二维码大小
    CGRect extent = CGRectIntegral(outputImg.extent);
    CGFloat scale = MIN(150/CGRectGetWidth(extent), 150/CGRectGetHeight(extent));
    //创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:outputImg fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    //保存bitmap到图片
    scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

-(void)dealloc
{
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(scaledImage);
}
@end
